const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const ObjectId = mongoose.Types.ObjectId;
const { BASE_URL, DEFAULT_IAMGE } = require('../../../config');
const { User, friendList, groupChat } = require('../../../models')
const { SECRETKEY } = require('../../../config');

// 注册
function signup(io, socket, data, callback) {
    User.findOne({ phone: data.phone }).then(res => {
        if (res === null) {
            User.create({ nickname: data.nickName, phone: data.phone, password: data.password })
            .then(res => {
                const token = jwt.sign({ id: res._id.toString(), nickname: res.nickname }, SECRETKEY, { expiresIn: '1d' });
                callback({ status_code: 200, info: "注册成功", data: res, token })
            })
        } else {
            callback({ status_code: 404, info: "改手机号已被注册" });
        }
    });
}

// 登录
function login(io, socket, data, callback) {
    User.findOne(
        { phone: data.phone, password: data.password }, 
        { password: 0, __v: 0, createdAt: 0, socketId: 0, draft: 0, DynamicList: 0 }
    )
    .then(res => {
        if (res === null) {
            callback({ status_code: 404, info: "没有改用户" })
        } else {
            res.socketId = socket.id
            res.save().then(() => { 
                let data = res;

                (data.headImgUrl != DEFAULT_IAMGE) && (data.headImgUrl = BASE_URL + data.headImgUrl);
                (data.cover != DEFAULT_IAMGE) && (data.cover = BASE_URL + data.cover);

                console.log(res.phone + '登录成功');
                
                res.joinedGroups.forEach(item => socket.join(item.toString())); //连接到群聊

                const token = jwt.sign({ id: data._id.toString(), nickname: data.nickname }, SECRETKEY, { expiresIn: '1d' });

                callback({ status_code: 200, info: "登录成功", data, token });
            })
        }
    });
}

// 发信息
function sendMessage(io, socket, data, callback) {
    data.sender = new ObjectId(data.sender);
    data.addresser = new ObjectId(data.addresser);
    if (!data.is_groupChat) {
        User.findOne({ _id: data.addresser }, { socketId: 1, phone: 1 })
        .then(res => {
            if (res.socketId != "") {
                socket.to(res.socketId).emit('receive_message_friend', data)
            }
            friendList.findOne({ phone: res.phone }, { friends: 1 })
            .then(res => {
                if (res == null) {
                    console.log('查找用户失败 loginView.socket');
                    return;
                }
                res.friends.find(item => toString(item.friendId) == toString(data.sender))
                .messages
                .push(data);
                res.save();
            })
        })
        User.findOne({ _id: data.sender }, { phone: 1 })
        .then(res => {
            friendList.findOne({ phone: res.phone }, { friends: 1 })
            .then(res => {
                if (res == null) {
                    console.log('查找用户失败 loginView.socket');
                    return;
                }
                res.friends.find(item => toString(item.friendId) == toString(data.addresser))
                .messages
                .push(data);
                res.save();
            })
        })
    } else {
        groupChat.findOne({ _id: data.addresser })
        .then(res => {
            io.to(data.addresser.toString()).emit('receive_message_groupChat', data);
            res.messages.push(data);
            res.save()
        })
    }
}

// 发送好友列表
function sendFriendList(io, socket, data, callback) {
    friendList.findOne({ phone: data })
    .populate({ 
        path: "friends", 
        populate: [
            { path: "friendId", select: "headImgUrl nickname phone socketId upvote DynamicList" }
        ]
    })
    .then(res => {
        if (res != null) {
            callback({ status_code: 200, friends: res.friends });
            return;
        }
        callback({ status_code: 200, friends: [] });
    })
    .catch(err => callback({ status_code: 404, error: err }))
}

// 获取好友申请list
function getApplications(io, socket, data, callback) {
    User.findOne({ phone: data }, { applications: 1 })
    .populate({
        path: 'applications', 
        populate: [
            { path: "sender", select: "headImgUrl nickname" },
            { path: "receiver", select: "headImgUrl nickname" },
        ]
    })
    .then(res => {
        if (res != null) {
            callback({ state: 200, data: res.applications })
        }
    })
}

// 获取群聊
function getGroupChats(io, socket, data, callback) {
    User.findOne({ phone: data })
    .populate({
        path: "joinedGroups",
        populate: [
            { path: "owner" },
            { path: "members" }
        ]
    })
    .then(res => {
        // 给群聊头像补完链接
        res.joinedGroups.forEach(item => item.groupAvatar = BASE_URL + item.groupAvatar)
        callback({ status_code: 200, data: res.joinedGroups })
    })
    .catch(err => callback({ status_code: 404, data: err }));
}

// 连接到群聊
function connectToGroupChats(io, socket, data, callback) {
    User.findOne({ phone: data })
    .then(res => {
        res.joinedGroups.forEach(item => socket.join(item.toString()));
    })
}

// 删除好友
async function delFriend(io, socket, data, callback) {
    try {
        let { userPhone, friendId } = data;
        console.log('删除好友：', userPhone, friendId);
        
        // 1. 获取当前用户和好友的用户信息
        const currentUser = await User.findOne({ phone: userPhone });
        if (!currentUser) {
            socket.emit('delFriendError', { code: 404, message: '当前用户不存在' });
            return callback && callback({ status_code: 404, info: '当前用户不存在' });
        }
        
        const friendUser = await User.findOne({ _id: new ObjectId(friendId) });
        if (!friendUser) {
            socket.emit('delFriendError', { code: 404, message: '好友用户不存在' });
            return callback && callback({ status_code: 404, info: '好友用户不存在' });
        }
        
        // 2. 从当前用户的好友列表中删除对方
        const currentUserResult = await friendList.updateOne(
            { phone: userPhone }, 
            { $pull: { friends: { friendId: new ObjectId(friendId) } } }
        );
        
        // 3. 从对方的好友列表中删除当前用户
        const friendUserResult = await friendList.updateOne(
            { phone: friendUser.phone }, 
            { $pull: { friends: { friendId: currentUser._id } } }
        );
        
        if (currentUserResult.modifiedCount === 0 && friendUserResult.modifiedCount === 0) {
            // 如果没有文档被修改，可能是没有匹配到用户或者好友关系不存在
            socket.emit('delFriendError', { code: 404, message: '未找到匹配的好友关系，删除失败' });
            return callback && callback({ status_code: 404, info: '未找到匹配的好友关系，删除失败' });
        }
        
        // 4. 获取更新后的当前用户好友列表
        const updatedCurrentUserFriendList = await friendList.findOne({ phone: userPhone })
            .populate({ 
                path: "friends", 
                populate: [
                    { path: "friendId", select: "headImgUrl nickname phone socketId upvote DynamicList" }
                ]
            });
            
        // 5. 获取更新后的对方好友列表
        const updatedFriendUserFriendList = await friendList.findOne({ phone: friendUser.phone })
            .populate({ 
                path: "friends", 
                populate: [
                    { path: "friendId", select: "headImgUrl nickname phone socketId upvote DynamicList" }
                ]
            });
            
        // 6. 如果对方在线，通知对方被删除
        if (friendUser.socketId) {
            io.to(friendUser.socketId).emit('friendDeleted', { 
                code: 200, 
                message: `您已被 ${currentUser.nickname} 删除好友`,
                deletedBy: {
                    userId: currentUser._id,
                    nickname: currentUser.nickname,
                    phone: currentUser.phone
                },
                friends: updatedFriendUserFriendList ? updatedFriendUserFriendList.friends : []
            });
        }
            
        // 7. 通过socket返回更新后的好友列表给当前用户
        socket.emit('delFriendSuccess', { 
            code: 200, 
            message: '删除好友成功',
            friends: updatedCurrentUserFriendList ? updatedCurrentUserFriendList.friends : []
        });
        
        // 8. 如果有回调函数，也通过回调返回结果
        callback && callback({ 
            status_code: 200, 
            info: '删除好友成功',
            friends: updatedCurrentUserFriendList ? updatedCurrentUserFriendList.friends : [] 
        });
        
    } catch (err) {
        console.error('删除好友出错:', err);
        socket.emit('delFriendError', { code: 500, message: '删除好友失败: ' + err.message });
        callback && callback({ status_code: 500, info: '删除好友失败: ' + err.message });
    }
}

// 更新好友分组
async function updateFriendGroup(io, socket, data, callback) {    
    try {        
        const { phone, friendId, groupName } = data;                
        // 验证参数        
        if (!phone || !friendId || groupName === undefined) {            
            return callback({ code: 400, message: '参数不完整' });        
        }                
        // 更新好友分组
        const result = await friendList.updateOne(
            { phone, 'friends.friendId': friendId },
            { $set: { 'friends.$.friendGroup': groupName } }
        );
        if (result.modifiedCount === 0) {
            return callback({ code: 404, message: '未找到匹配的好友记录' });
        }
        // 获取更新后的好友列表
        const updatedFriendList = await friendList.findOne({ phone })
            .populate({ 
                path: "friends", 
                populate: [
                    { path: "friendId", select: "headImgUrl nickname phone socketId upvote DynamicList" }
                ]
            });
        // 返回更新成功和更新后的好友列表
        callback({ code: 200, message: '更新好友分组成功', friends: updatedFriendList.friends });
    } catch (error) {
        console.error('更新好友分组失败:', error);
        callback({ code: 500, message: '更新好友分组失败: ' + error.message });
    }
}

module.exports = {
    signup,
    login,
    sendMessage,
    getApplications,
    sendFriendList,
    getGroupChats,    
    connectToGroupChats,    
    delFriend,   
    updateFriendGroup,
}